package com.jrx.anytxn.param.service.product.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.dto.product.PaymentSequenceTableReq;
import com.jrx.anytxn.param.dto.product.PaymentSequenceTableRes;
import com.jrx.anytxn.param.entity.PrPaymentSequenceFactorTable;
import com.jrx.anytxn.param.entity.PrPaymentSequenceTable;
import com.jrx.anytxn.param.mapper.ext.ExtPaymentSequenceFactorTableMapper;
import com.jrx.anytxn.param.mapper.ext.ExtPaymentSequenceTableMapper;
import com.jrx.anytxn.param.service.product.IPaymentSequenceTableService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * 还款顺序处理
 *
 * @author : zhenghaopu
 * 2019/12/5
*/
@Service
@CacheConfig(cacheNames = "PAYMENT_SEQ")
public class PaymentSequenceTableServiceImpl implements IPaymentSequenceTableService {
    private static final Logger logger = LoggerFactory.getLogger(PaymentSequenceTableServiceImpl.class);

    @Resource
    private ExtPaymentSequenceTableMapper extPaymentSequenceTableMapper;

    @Resource
    private ExtPaymentSequenceFactorTableMapper extPaymentSequenceFactorTableMapper;

    @Autowired
    private ISegmentService segmentService;

    @Override
    public TxnPage<PaymentSequenceTableRes> findAllPageByTenId(Integer pageNum, Integer pageSize, String tenantId) throws TxnException {
        Page<PrPaymentSequenceTable> page = PageHelper.startPage(pageNum, pageSize,Constant.ORDER_BY_SORT);
        List<PrPaymentSequenceTable> prPaymentSequenceTableList = extPaymentSequenceTableMapper.selectByTenId(tenantId);
        if (prPaymentSequenceTableList.isEmpty()) {
            logger.error("查询还款顺序列表不存在");
            throw new TxnException(TxnRespCode.NO_DATA.getMsg());
        }
        List<PaymentSequenceTableRes> res = BeanMapping.copyList(prPaymentSequenceTableList, PaymentSequenceTableRes.class);
        return new TxnPage<>(pageNum, pageSize, page.getTotal(), res);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PaymentSequenceTableRes addPaymentSequenceTable(PaymentSequenceTableReq paymentSequenceTableReq) throws TxnException {
        PrPaymentSequenceTable prPaymentSequenceTable = BeanMapping.copy(paymentSequenceTableReq, PrPaymentSequenceTable.class);
        /*根据还款顺序ID和机构号ID查看数据库表里是否已存在此信息,若存在抛出异常*/
        PrPaymentSequenceTable payment = extPaymentSequenceTableMapper.selectByPaymentSequenceIdAndTenId(prPaymentSequenceTable.getTenantId(), prPaymentSequenceTable.getPaymentSequenceId());
        if (payment != null) {
            logger.error("机构号为{}与还款顺序ID为{}的信息已存在", prPaymentSequenceTable.getOrganizationId(), prPaymentSequenceTable.getPaymentSequenceId());
            throw new TxnException(TxnRespCode.DATA_EXISTS, TxnRespCode.DATA_EXISTS.getMsg());
        }
        /*查看此还款顺序下的账户类型是否相同*/
        /*List<PrPaymentSequenceFactorTable> prPaymentSequenceFactorTableList = paymentSequenceTableReq.getControlReqList();
        Set<PrPaymentSequenceFactorTable> set = new TreeSet<>((o1, o2) -> {
            //==0表示重复
            int compareToResult = 1;
            if (o1.getAccountType().equalsIgnoreCase(o2.getAccountType())) {
                compareToResult = 0;
            }
            return compareToResult;
        });
        set.addAll(prPaymentSequenceFactorTableList);
        if (new ArrayList<>(set).size() != prPaymentSequenceFactorTableList.size()) {
            logger.error("账号类型重复");
            throw new TxnException("账号类型不能重复！");
        }*/
        /*增加或复制还款顺序信息*/
        try {
            prPaymentSequenceTable.setId(segmentService.getId(Constant.PR_PAYMENTSEQUENCETABLE));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnException(ErrorMsgConstant.ERROR_ID);
        }

        prPaymentSequenceTable.setRecordVersionNumber(Constant.VERSION_NUMBER);
        extPaymentSequenceTableMapper.insertSelective(prPaymentSequenceTable);

        /*增加或复制还款顺序因子信息*/
        List<PrPaymentSequenceFactorTable> list = paymentSequenceTableReq.getControlReqList();
        for (PrPaymentSequenceFactorTable factor : list) {
            try {
                factor.setId(segmentService.getId(Constant.PR_PAYMENT_SEQUENCE_FACTOR_TABLE));
            } catch (SegmentException e) {
                logger.error("主键生成错误",e);
                throw new TxnException(ErrorMsgConstant.ERROR_ID);
            }
            factor.setTenantId(paymentSequenceTableReq.getTenantId());
            factor.setUpdateBy(paymentSequenceTableReq.getUpdateBy());
            factor.setPaymentSequenceId(paymentSequenceTableReq.getPaymentSequenceId());
            factor.setOrganizationId(paymentSequenceTableReq.getOrganizationId());
            factor.setRecordVersionNunmber(Constant.VERSION_NUMBER);
            extPaymentSequenceFactorTableMapper.insertSelective(factor);
        }
        return BeanMapping.copy(prPaymentSequenceTable, PaymentSequenceTableRes.class);
    }

    @CacheEvict(key = "'paymentSeq_'+#paymentSequenceTableReq.tenantId+'_'+#paymentSequenceTableReq.paymentSequenceId")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PaymentSequenceTableRes modifyPaymentSequenceTable(PaymentSequenceTableReq paymentSequenceTableReq) throws TxnException {
        PrPaymentSequenceTable prPaymentSequenceTable = BeanMapping.copy(paymentSequenceTableReq, PrPaymentSequenceTable.class);
        /*查看此还款顺序下的账户类型是否相同*/
        /*List<PrPaymentSequenceFactorTable> prPaymentSequenceFactorTableList = paymentSequenceTableReq.getControlReqList();
        Set<PrPaymentSequenceFactorTable> set = new TreeSet<>((o1, o2) -> {
            //==0表示重复
            int compareToResult = 1;
            if (o1.getAccountType().equalsIgnoreCase(o2.getAccountType())) {
                compareToResult = 0;
            }
            return compareToResult;
        });
        set.addAll(prPaymentSequenceFactorTableList);
        if (new ArrayList<>(set).size() != prPaymentSequenceFactorTableList.size()) {
            logger.error("账号类型重复");
            throw new TxnException("账号类型不能重复！");
        }*/
        /*修改还款顺序表信息*/
        extPaymentSequenceTableMapper.updateByPaymentSequenceIdAndTenId(prPaymentSequenceTable);
        /*修改还款顺序因子表信息(先删除后增加)*/
        PrPaymentSequenceFactorTable prPaymentSequenceFactorTable = new PrPaymentSequenceFactorTable();
        prPaymentSequenceFactorTable.setTenantId(prPaymentSequenceTable.getTenantId());
        prPaymentSequenceFactorTable.setPaymentSequenceId(prPaymentSequenceTable.getPaymentSequenceId());
        List<PrPaymentSequenceFactorTable> factorTableList = extPaymentSequenceFactorTableMapper.selectByPaymentSequenceIdAndTenId(prPaymentSequenceFactorTable.getPaymentSequenceId(), prPaymentSequenceFactorTable.getTenantId());
        if (factorTableList != null && !factorTableList.isEmpty()) {
            for (PrPaymentSequenceFactorTable factorTable : factorTableList) {
                extPaymentSequenceFactorTableMapper.deleteByPaymentSequenceIdAndTenId(factorTable.getPaymentSequenceId(),factorTable.getTenantId());
            }
        }

        List<PrPaymentSequenceFactorTable> list = paymentSequenceTableReq.getControlReqList();
        for (PrPaymentSequenceFactorTable pr : list) {
            try {
                pr.setId(segmentService.getId(Constant.PR_PAYMENT_SEQUENCE_FACTOR_TABLE));
            } catch (SegmentException e) {
                logger.error("主键生成错误",e);
                throw new TxnException(ErrorMsgConstant.ERROR_ID);
            }
            pr.setTenantId(prPaymentSequenceTable.getTenantId());
            pr.setPaymentSequenceId(prPaymentSequenceTable.getPaymentSequenceId());
            pr.setOrganizationId(prPaymentSequenceTable.getOrganizationId());
            pr.setUpdateBy(prPaymentSequenceTable.getUpdateBy());
            pr.setRecordVersionNunmber(prPaymentSequenceTable.getRecordVersionNumber()==null?1:prPaymentSequenceTable.getRecordVersionNumber());
            extPaymentSequenceFactorTableMapper.insertSelective(pr);
        }
        return BeanMapping.copy(prPaymentSequenceTable, PaymentSequenceTableRes.class);
    }

    @Cacheable(key = "'paymentSeq_'+#tenantId+'_'+#paymentSequenceId")
    @Override
    public PaymentSequenceTableRes getByTenIdAndPaymentSequenceId(String tenantId, String paymentSequenceId) {
        /*根据租户ID和还款顺序ID查询还款顺序表信息*/
        PrPaymentSequenceTable prPaymentSequenceTable = extPaymentSequenceTableMapper.selectByPaymentSequenceIdAndTenId(tenantId, paymentSequenceId);

        /*获取查询信息的还款顺序id和租户ID查询还款顺序因子表里的相关信息列表*/
        PrPaymentSequenceFactorTable prPaymentSequenceFactorTable = new PrPaymentSequenceFactorTable();
        prPaymentSequenceFactorTable.setTenantId(prPaymentSequenceTable.getTenantId());
        prPaymentSequenceFactorTable.setPaymentSequenceId(prPaymentSequenceTable.getPaymentSequenceId());
        List<PrPaymentSequenceFactorTable> prPaymentSequenceFactorTableList = extPaymentSequenceFactorTableMapper.selectByPaymentSequenceIdAndTenId(prPaymentSequenceFactorTable.getPaymentSequenceId(), prPaymentSequenceFactorTable.getTenantId());
        PaymentSequenceTableRes res = BeanMapping.copy(prPaymentSequenceTable, PaymentSequenceTableRes.class);
        res.setControlReqList(prPaymentSequenceFactorTableList);
        return res;
    }

    @Override
    @CacheEvict(key = "'paymentSeq_'+#tenantId+'_'+#paymentSequenceId")
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeByTenIdAndPaymentSequenceId(String tenantId, String paymentSequenceId) throws TxnException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(paymentSequenceId)) {
            logger.error("还款顺序主键ID不存在");
            throw new TxnException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        /*根据租户ID和还款顺序ID查询信息*/
        PrPaymentSequenceTable prPaymentSequenceTable = extPaymentSequenceTableMapper.selectByPaymentSequenceIdAndTenId(tenantId, paymentSequenceId);
        /*根据还款顺序ID和租户ID查询还款顺序因子表信息*/
        PrPaymentSequenceFactorTable prPaymentSequenceFactorTable = new PrPaymentSequenceFactorTable();
        prPaymentSequenceFactorTable.setTenantId(prPaymentSequenceTable.getTenantId());
        prPaymentSequenceFactorTable.setPaymentSequenceId(prPaymentSequenceTable.getPaymentSequenceId());
        List<PrPaymentSequenceFactorTable> list = extPaymentSequenceFactorTableMapper.selectByPaymentSequenceIdAndTenId(prPaymentSequenceFactorTable.getPaymentSequenceId(), prPaymentSequenceFactorTable.getTenantId());
        if (list != null) {
            for (PrPaymentSequenceFactorTable pr : list) {
                extPaymentSequenceFactorTableMapper.deleteByPaymentSequenceIdAndTenId(pr.getPaymentSequenceId(), pr.getTenantId());
            }
        }
        int a = extPaymentSequenceTableMapper.deleteByPaymentSequenceIdAndTenId(tenantId, paymentSequenceId);
        return a > 0;
    }
}
